package com.bear.newsset.widget;

import android.content.Context;
import android.graphics.Typeface;
import androidx.annotation.ColorRes;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.bear.newsset.R;
import com.bear.newsset.util.Utils;

import java.util.List;

/**
 * 新闻分类列表
 */
public class SiteTableView extends HorizontalScrollView {
    private final float ITEM_TEXT_SIZE = 20;
    private Context mContext;
    private AttributeSet mAttrs;
    private RadioGroup rgLayoutView;
    private List<ItemConfig> configList;
    private int screenWidth;
    private int dp8, dp4;

    /**
     * 子项选中事件监听器
     */
    public interface OnItemSelectedListener {
        void onItemSelected(RadioGroup radioGroup, ItemConfig config, int position);
    }

    public SiteTableView(Context context) {
        super(context);
        init(context);
    }

    public SiteTableView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mAttrs = attrs;
        init(context);
    }

    private void init(Context mContext) {
        this.mContext = mContext;
        screenWidth = mContext.getResources().getDisplayMetrics().widthPixels;
        dp8 = Utils.dp2Px(mContext, 8);
        dp4 = Utils.dp2Px(mContext, 4);
        initView();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        //创建选项组
        rgLayoutView  = new RadioGroup(mContext);
        /* 设置宽高 */
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(mContext, mAttrs);
        lp.width = LinearLayout.LayoutParams.MATCH_PARENT;
        lp.height = LinearLayout.LayoutParams.WRAP_CONTENT;
        setLayoutParams(lp);
        //不显示滚动条
        setHorizontalScrollBarEnabled(false);
//        setPadding(0, dp5, 0, dp5);
        //背景显示底部分割线
//        setBackgroundResource(R.drawable.layer_btm_line);
        /* ===== */
        addView(rgLayoutView);                                  //添加到父布局
        rgLayoutView.setLayoutParams(lp);                       //设置选项组宽高（必须在添加父布局之后）
        rgLayoutView.setOrientation(RadioGroup.HORIZONTAL);     //水平排列
        rgLayoutView.setGravity( Gravity.CENTER );
    }

    /**
     * 创建一个子View
     * @param ic                  文本内容
     */
    private RadioButton createItemView(final ItemConfig ic) {

        final RadioButton item = new RadioButton(mContext);
        int iconResId = ic.getIconResId();
        int bgResId = ic.getBackgroundResId();

        item.setText(ic.getItemText());                                             //文本内容
        item.setTextSize( ITEM_TEXT_SIZE );                                         //字体大小
        item.setTextColor( getResources().getColor(ic.getTextUnCheckColor()) );     //文本默认颜色
        item.setPadding(dp8, dp4, dp8, dp4);                                //设置内边距
        //设置图标
        item.setButtonDrawable( iconResId > 0 ? getResources().getDrawable(iconResId) : null);
        //设置背景(设置白色背景是为了去掉button默认的点击效果)
        if( bgResId > 0 ) { item.setBackgroundResource( bgResId ); }

        //item选中事件监听器
        item.setOnCheckedChangeListener((compoundButton, b) -> {
            int color = b ? ic.getTextCheckColor() : ic.getTextUnCheckColor();
            int style = b ? Typeface.BOLD : Typeface.NORMAL;
            item.setTextColor(getResources().getColor(color));
            item.setTypeface(Typeface.defaultFromStyle(style));
        });
        return item;
    }

    /**
     * 设置item列表
     * @param configList    配置列表
     */
    public void setItemList(List<ItemConfig> configList) {
        this.configList = configList;
        RadioButton item;
        for( ItemConfig ic : configList ) {
            item = createItemView( ic );
            //将item加入到选项组
            rgLayoutView.addView(item);
        }
        //设置第一个item为选中状态
        rgLayoutView.check( rgLayoutView.getChildAt(0).getId() );
        //关注当前下标的Item
        setItemFocus( 0 );
    }

    public void setItemTextColorAll(@ColorRes int colorRes, boolean isContainsSelected) {
        for (int i = 0; i < rgLayoutView.getChildCount(); i++) {
            if( !isContainsSelected && i == 0 ) continue;
            RadioButton rb = (RadioButton) rgLayoutView.getChildAt( i );
            rb.setTextColor( getResources().getColor( colorRes ) );
        }
    }

    public void setDefaultItemTextColorAll(boolean isContainsSelected) {
        setItemTextColorAll(R.color.colorWhite, isContainsSelected);
    }

    /**
     * 设置子项选中事件监听器
     * @param mItemSelectedListener     子项选中事件监听器
     */
    public void setOnItemSelectedListener(final OnItemSelectedListener mItemSelectedListener) {
        rgLayoutView.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                RadioButton v = findViewById(i);
                int index = radioGroup.indexOfChild( v );
                //关注当前下标的Item
                setItemFocus( --i );
                //回调选中监听器
                mItemSelectedListener.onItemSelected(radioGroup, configList.get(index) , index);
                scrollToFocus();//滑动到item的焦点处
            }
        });
    }

    /**
     * 关注当前下标的Item
     * 关注的下标Item字体放大、加粗
     * @param index     下标
     */
    public void setItemFocus(int index) {
        for (int i = 0; i < rgLayoutView.getChildCount(); i++) {
            RadioButton v = (RadioButton) rgLayoutView.getChildAt( i );
            float size = index == i ? 24 : ITEM_TEXT_SIZE;
            v.setTextSize( size );
            v.getPaint().setFakeBoldText( index == i );
        }
    }

    /**
     * 选中指定的item
     * @param position      当前位置
     */
    public void setItemSelected(int position) {
        ((RadioButton)rgLayoutView.getChildAt(position)).setChecked(true);
    }

    /**
     * 滑动到item的焦点处
     */
    private void scrollToFocus() {
        //获取滑动列表中的子控件（RadioGroup）选中的View
        View item = findViewById(rgLayoutView.getCheckedRadioButtonId());
        //选中item（View）的X坐标
        int x = (int) item.getX();
        /* item坐标是否小于屏幕，大于屏幕则将HorizontalScrollView滑动到item的X坐标位置，否则重置
           x坐标 + view的宽度是为了防止当前view的一半位置小于屏幕而不自动滑动 */
        if( x + item.getWidth() < screenWidth  ) { x = 0; }
        //滑动HorizontalScrollView
        smoothScrollTo(x, (int) getY());
    }

    /**
     * Item配置
     */
    public static class ItemConfig {
        private String itemText;
        private @ColorRes int textCheckColor = R.color.colorBlack;          //选中文本颜色
        private @ColorRes int textUnCheckColor = R.color.colorDefaultText;  //未选中文本颜色
        private int iconResId;
        private int backgroundResId;

        public String getItemText() {
            return itemText;
        }

        public ItemConfig setItemText(String itemText) {
            this.itemText = itemText;
            return this;
        }

        public int getTextCheckColor() {
            return textCheckColor;
        }

        public ItemConfig setTextCheckColor(int textCheckColor) {
            this.textCheckColor = textCheckColor;
            return this;
        }

        public int getTextUnCheckColor() {
            return textUnCheckColor;
        }

        public ItemConfig setTextUnCheckColor(int textUnCheckColor) {
            this.textUnCheckColor = textUnCheckColor;
            return this;
        }

        public int getIconResId() {
            return iconResId;
        }

        public ItemConfig setIconResId(int iconResId) {
            this.iconResId = iconResId;
            return this;
        }

        public int getBackgroundResId() {
            return backgroundResId;
        }

        public ItemConfig setBackgroundResId(int backgroundResId) {
            this.backgroundResId = backgroundResId;
            return this;
        }

        @Override
        public String toString() {
            return "ItemConfig{" +
                    "itemText='" + itemText + '\'' +
                    ", textCheckColor=" + textCheckColor +
                    ", textUnCheckColor=" + textUnCheckColor +
                    ", iconResId=" + iconResId +
                    ", backgroundResId=" + backgroundResId +
                    '}';
        }
    }
}
